package stark.app.function.calculator;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SizeUtils;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.stark.calculator.science.CalDbManager;
import com.stark.calculator.science.CalRecord;

import java.util.List;

import stark.app.R;
import stark.app.databinding.ActivityCalRecordBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.utils.DialogUtil;

/**
 * Author：daizhongbin on 2024/11/8
 * Email：1027154338@qq.com
 * Desc:
 */
public class CalRecordActivity extends BaseNoModelActivity<ActivityCalRecordBinding> {

    private CalRecordAdapter mRecordAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_cal_record;
    }

    @Override
    protected void initView() {
        mDataBinding.ivBack.setOnClickListener(v -> {
            onBackPressed();
        });
        mDataBinding.tvDel.setOnClickListener(v -> {
            showDelDialog();
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mDataBinding.rvContainer.setLayoutManager(layoutManager);
        mDataBinding.rvContainer.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int bottom = SizeUtils.dp2px(10);
                outRect.set(0, 0, 0, bottom);
            }
        });
        mRecordAdapter = new CalRecordAdapter();
        mDataBinding.rvContainer.setAdapter(mRecordAdapter);
    }

    @Override
    protected void initData() {
        CalDbManager.instance().calRecordDao().getAllForLiveData().observe(this, new Observer<List<CalRecord>>() {
            @Override
            public void onChanged(List<CalRecord> calRecords) {
                if (calRecords == null || calRecords.size() == 0) {
                    mDataBinding.tvNoData.setVisibility(View.VISIBLE);
                } else {
                    mDataBinding.tvNoData.setVisibility(View.GONE);
                }
                mRecordAdapter.setNewInstance(calRecords);
            }
        });
    }

    private void showDelDialog() {
        DialogUtil.asConfirm(this, "提示", "确认清除所有记录吗？", "取消", "确定", new OnConfirmListener() {
            @Override
            public void onConfirm() {
                CalDbManager.instance().calRecordDao().delBatch(mRecordAdapter.getData());
            }
        }, null, false);
    }
}
